// 引入编写好的api
const api = require('./api')
// 引入文件模块
const fs = require('fs')
// 引入处理路径的模块
const path = require('path')
// 引入处理post数据的模块
const bodyParser = require('body-parser')
// 引入Express
const express = require('express')
const app = express()
// 轮询 WebSocket 1
// var WebSocket = require('ws')
// const wss = new WebSocket.Server({ port: 8080 })
// console.log('111sss1', wss)
// module.exports.wss = wss
// wss.on('connection', function connection (ws) {
//   console.log(ws, '4324234')
//   ws.on('message', function incoming (message) {
//     console.log(message, '4324234')
//   })
//   ws.send('fsdfsd')
// })
// 跨域
let cors = require('cors')
app.use(cors())

// app.use(bodyParser.json())
// app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json({limit: '50mb'}))
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}))
app.use(api)
// 访问静态资源文件 这里是访问所有dist目录下的静态资源文件
app.use(express.static(path.resolve(__dirname, '../dist')))

// 允许跨域访问  也可以通过npm cors进行设置=
app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', 'X-Requested-With')
  res.header('Access-Control-Allow-Headers', 'Content-Type')
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS')
  if (req.method === 'OPTIONS') {
    res.send(200)
  } else {
    next()
  }
})
// 因为是单页应用 所有请求都走/dist/index.html
app.get('*', function (req, res) {
  const html = fs.readFileSync(path.resolve(__dirname, '../dist/index.html'), 'utf-8')
  res.send(html)
})
// 监听8088端口
app.listen(8088)
console.log('监听成功....')
